import { useRef, useState } from "react";
import styles from "./index.module.less";
import { ProFormInstance } from "@ant-design/pro-components";
import { Steps } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { getTaskDetail, getTaskProcess } from "@/api/modules/task";
import { getLineDetail } from "@/api/modules/line";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import AMap from "@/components/AMap";
import { Descriptions } from "antd";
import cs from "classnames";
import { getTaskLevelDict, getDictByCode } from "@/api/modules/dict";
import { find, map } from "lodash";
import { PageContainer } from "@ant-design/pro-layout";
import { ROUTE_TYPE_ENUM } from "../Add/constant";
import { getPathByScID } from "@/api/modules/platform";
import useWebSocket from "@/store/hooks/useWebSocket";
import { createVehicleInfoContent, createMarkerInfoWindowConfig } from "@/utils/infoWindowUtils";
import { getCarDetail } from "@/api/modules/device";
import { yawToAngle } from "@/utils/utils";

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const [detailInfo, setDetailInfo] = useState<any>({});
	const [loopMarker, setLoopMarker] = useState<any[]>([]); //环线点位列表
	const [progressList, setProgressList] = useState<any>([]); //环线点位列表
	const [linePolygons, setLinePolygons] = useState<any[]>([]); // 环线场景范围
	const [linePolylinePaths, setLinePolylinePaths] = useState<any[]>([]); // 环线路径
	
	// 新增：WebSocket相关状态
	const [realTimePoint, setRealTimePoint] = useState<any>(null); //车辆实时位置
	const [realTimeData, setRealTimeData] = useState<any>(null); //车辆实时数据
	const [vinCode, setVinCode] = useState<string | null>(null); //VIN码
	const { data: data1 } = useRequest(() => getTaskLevelDict({ parentId: 0, code: "JOB_STATUS" }));
	const { data: data2 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_TYPE" }));
	const { data: data3 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_ROUTE" }));
	const { data: data4 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_VEHICLE" }));
	const { data: data5 } = useRequest(() => getTaskProcess({ id: detailId }));
	const { data: data6 } = useRequest(() => getDictByCode({ parentId: 0, code: "POINT_TYPE" }));
	const taskStatusList = data1?.data;
	const taskTypeList = data2?.data;
	const taskRouteList = data3?.data;
	const carTypeList = data4?.data;
	const progressData = data5?.data;
	const pointTypeList = data6?.data;

	const { loading: loadingDetail, runAsync: getDetailAsync, data: walkDetailInfo } = useRequest(getTaskDetail, { manual: true });

	// WebSocket连接，当VIN码存在时建立连接
	useWebSocket({
		url: vinCode ? `wss://software.hugesuccess.cn/ws/realtime/${vinCode}` : "",
		onMessage: data => {
			const result = data?.data;
			setRealTimePoint({
				position: [result?.longitude, result?.latitude],
				title: "车辆实时位置",
				icon: "/images/icon-map-car.png",
				hoverText: "车辆实时位置",
				angle: yawToAngle(result?.yaw, "deg"),
				// 添加车辆基本信息
				vehicleInfo: {
					plateNo: detailInfo?.plateNo,
					vin: vinCode,
					vehicleType: detailInfo?.vehType,
					soc: result?.soc,
					speed: result?.speed,
					yaw: result?.yaw,
					vehicleStatus: result?.vehicleStatus,
					taskStatus: result?.taskStatus,
					anomalousStatus: result?.anomalousStatus
				},
				// 配置信息窗口
				infoWindow: {
					content: createVehicleInfoContent({
						plateNo: detailInfo?.plateNo,
						vin: vinCode,
						vehicleType: detailInfo?.vehType,
						soc: result?.soc,
						speed: result?.speed,
						yaw: result?.yaw,
						vehicleStatus: result?.vehicleStatus,
						taskStatus: result?.taskStatus,
						anomalousStatus: result?.anomalousStatus
					}),
					showOnHover: true,
					showOnClick: false,
					offset: [0, -30],
					closeWhenClickMap: true
				}
			});
			setRealTimeData(result);
		}
	});

	// 根据任务状态获取样式类名
	const getStatusClass = (jobStatus: number) => {
		switch(jobStatus) {
			case 0:
				return styles.warning
			case 1:
				return styles.success
			case 2:case 4:case 5:
				return styles.gray
			case 3:
				return styles.error
			default:
				return styles.gray
		}
	};

	//获取环线详情
	const handleGetLineDetail = async (lineId: string) => {
		if (!lineId) {
			setLinePolygons([]);
			setLoopMarker([]);
			return;
		}
		try {
			const res: any = await getLineDetail({ id: lineId });
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				// 处理场景范围数据 (polygons)
				const polygons = map(data?.sceneList || [], (scene: any) => {
					try {
						const points = JSON.parse(scene?.points || '[]');
						return {
							path: points,
							strokeColor: scene?.color || "#01B2A8",
							fillColor: scene?.color || "#01B2A8",
							strokeWeight: 2
						};
					} catch (error) {
						console.error('解析场景范围数据失败:', error);
						return null;
					}
				}).filter(Boolean);
				setLinePolygons(polygons);
				// 使用工具函数创建标记信息窗口配置

				// 处理环线标记点数据 (loopMarker)
				const markers = map(data?.siteList || [], (item: any) => {
					const position = item.lonLat?.split(',');
					const markerData = {
						name: item?.name,
						type: item?.type,
						callName: item?.callName,
						callPhone: item?.callPhone
					};
					return { 
						position: [position[0], position[1]],
						title: item?.name || '接驳点',
						icon: '/images/icon-joint.png',
						// 添加标记基本信息
						markerInfo: markerData,
						// 使用工具函数配置信息窗口
						infoWindow: createMarkerInfoWindowConfig(markerData, pointTypeList, {
							showOnHover: true,
							showOnClick: false,
							offset: [0, -30],
							closeWhenClickMap: true
						})
					};
				});
				setLoopMarker(markers);
			}
		} catch (error) {
			console.error('获取环线详情失败:', error);
			setLinePolygons([]);
			setLoopMarker([]);
		}
	};

	// 根据场景ID获取路线数据
	const handleGetPathsBySceneList = async (sceneList: any[]) => {
		if (!sceneList || sceneList.length === 0) {
			setLinePolylinePaths([]);
			return;
		}

		try {
			// 循环调用getPathByScID获取每个场景的路线
			const pathPromises = sceneList.map(async (scene: any) => {
				if (!scene.id) return null;
				try {
					const pathRes = await getPathByScID({ id: scene.id });
					if (Number(pathRes?.code) === RESULT_CODES.SUCCESS && pathRes?.data?.length > 0) {
						// 遍历pathRes.data数组中的每个元素，处理其routeSubList
						const allPaths = [];
						for (const pathData of pathRes.data) {
							const paths = map(pathData?.routeSubList || [], (item: any) => {
								return {
									path: JSON.parse(item.routeInfo || '[]'),
									strokeColor: pathData?.color || scene?.color || "#01B2A8"
								};
							});
							allPaths.push(...paths);
						}
						return allPaths;
					}
					return null;
				} catch (error) {
					console.error(`获取场景${scene.id}路线失败:`, error);
					return null;
				}
			});

			// 等待所有路线数据获取完成
			const allPaths = await Promise.all(pathPromises);
			// 过滤掉null值并展平数组
			const flatPaths = allPaths.filter(Boolean).flat();
			setLinePolylinePaths(flatPaths);
		} catch (error) {
			console.error('获取场景路线数据失败:', error);
			setLinePolylinePaths([]);
		}
	};

	useEffect(() => {
		if (!detailId || !pointTypeList) return;
		getDetailAsync({ id: detailId }).then(async (res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				setDetailInfo(data);
				// 设置车辆ID，用于获取车辆详情
				if (data?.vehId) {
					// 调用getCarDetail获取车辆信息，提取VIN码
					try {
						const carDetailRes = await getCarDetail({ id: data.vehId });
						console.log(carDetailRes, "carDetailRes");
						if (Number(carDetailRes?.code) === RESULT_CODES.SUCCESS) {
							const carData = carDetailRes?.data?.vehicleInfo ?? {};
							// 提取VIN码，根据实际API返回的字段名调整
							const vin = carData?.vin || carData?.vinCode || carData?.vehicleVin;
							if (vin) {
								setVinCode(vin);
							}
						}
					} catch (error) {
						console.error("调用getCarDetail失败:", error);
					}
				}
				const InitialData = {
					...data
				};
				// 判断是否为环线任务
				if (data?.rtType === ROUTE_TYPE_ENUM.loop) {
					// 如果是环线任务，获取环线详情
					if (data?.loopId) {
						await handleGetLineDetail(data.loopId);
					}
				} else {
					// 使用工具函数创建标记信息窗口配置
					setLoopMarker(map(data?.siteList || [], (item: any) => {
						const position = item.lonLat?.split(',')
						const markerData = {
							name: item?.name,
							type: item?.type,
							callName: item?.callName,
							callPhone: item?.callPhone
						};
						return { 
							position: [position[0], position[1]],
							title: item?.name || '接驳点',
							icon: '/images/icon-joint.png',
							// 添加标记基本信息
							markerInfo: markerData,
							// 使用工具函数配置信息窗口
							infoWindow: createMarkerInfoWindowConfig(markerData, pointTypeList, {
								showOnHover: true,
								showOnClick: false,
								offset: [0, -30],
								closeWhenClickMap: true
							})
						}
					}))
					// 处理非环线任务的场景范围数据 (polygons)
					const polygons = map(data?.sceneList || [], (scene: any) => {
						try {
							const points = JSON.parse(scene?.points || '[]');
							return {
								path: points,
								strokeColor: scene?.color || "#01B2A8",
								fillColor: scene?.color || "#01B2A8",
								strokeWeight: 2
							};
						} catch (error) {
							console.error('解析场景范围数据失败:', error);
							return null;
						}
					}).filter(Boolean);
					setLinePolygons(polygons);
					// 根据sceneList获取路线数据
					await handleGetPathsBySceneList(data?.sceneList || []);
				}
				formRef.current?.setFieldsValue(InitialData);
			}
		});
	}, [pointTypeList]);

	useEffect(() => {
		const result = map(progressData?.jobSteps, (item: any) => {
			return {
				title: item?.stepDescription,
				description: item?.stepTime
			}
		})
		setProgressList(result)
	}, [progressData])

	// 格式化数值显示
	const formatValue = (value: any) => {
		if (value === undefined || value === null) return "-";
		return parseFloat(Number(value).toFixed(2));
	};

	// 格式化状态显示
	const formatStatus = (value: any, type: string) => {
		if (value === undefined || value === null) return "-";
		switch (type) {
			case "vehicleStatus":
				return value === 1 ? "在线" : "离线";
			case "taskStatus":
				return value === 1 ? "作业中" : "空闲";
			case "anomalousStatus":
				return value === 1 ? "有故障" : "正常";
			default:
				return value;
		}
	};

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: "/task/list", breadcrumbName: "任务管理" },
					{ href: "", breadcrumbName: "任务详情" }
				],
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={cs(styles.detailContainer, "detailContainer")}>
					<div className={styles.container}>
						<div className={styles.content_wrap}>
							<div className={styles.content}>
								<div className={styles.moduleTitle}>基本信息</div>
								<Descriptions title="" column={1} labelStyle={{ width: "100px" }}>
									<Descriptions.Item label="任务编号">{detailInfo?.id}</Descriptions.Item>
									<Descriptions.Item label="任务名称">{detailInfo?.jobName}</Descriptions.Item>
									<Descriptions.Item label="任务类型">
										{find(taskTypeList, (item: any) => item.value === detailInfo?.jobType)?.label}
									</Descriptions.Item>
									<Descriptions.Item label="路线类型">
										{find(taskRouteList, (item: any) => item.value === detailInfo?.rtType)?.label}
									</Descriptions.Item>
									<Descriptions.Item label="车辆类型">
										{find(carTypeList, (item: any) => item.value === detailInfo?.vehType)?.label}
									</Descriptions.Item>
									<Descriptions.Item label="接驳点数量">{detailInfo?.countSite}</Descriptions.Item>
									<Descriptions.Item label="车牌号">{detailInfo?.plateNo}</Descriptions.Item>
								</Descriptions>
							</div>
						</div>
						<div className={cs(styles.content_wrap, styles.mt_20)}>
							<div className={styles.content}>
								<div className={styles.moduleTitle}>
									<div className={styles.title}>任务进度</div>
									<div className={cs(styles.status, getStatusClass(detailInfo?.jobStatus))}>
										<i></i>
										<span>{find(taskStatusList, (item: any) => item.value === detailInfo?.jobStatus)?.label}</span>
									</div>
								</div>
								<Steps progressDot current={progressList.length - 1} direction="vertical" items={progressList} />
							</div>
						</div>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap
								polylinePaths={linePolylinePaths}
								markers={loopMarker}
								polygons={linePolygons}
								realTimeMaker={realTimePoint}
							/>
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
